package com.fdb.smcts.redis.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;

import java.util.Objects;

/**
 * 需求编号:2019D08--
 * 问题编号:
 * 开发人员: caoxin
 * 创建日期:2019/11/26
 * 功能描述:
 * 修改日期:2019/11/26
 * 修改描述:
 */
public class CuratorLock {
    @Autowired
    @Qualifier("curatorFramework")
    private CuratorFrameworkFactory curatorFrameworkFactory;
    @Value("${dubbo.registry.address}")
    private String zkConnectPath;

    private CuratorFramework curatorFramework;

    public InterProcessMutex getLock(String key) {
        if (Objects.isNull(curatorFramework)) {
            curatorFramework = CuratorFrameworkFactory.builder().
                    connectString(zkConnectPath).
                    connectionTimeoutMs(5000).
                    retryPolicy(new ExponentialBackoffRetry(1000, 10)).
                    sessionTimeoutMs(3000).build();
        }
        if (!curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) {
            curatorFramework.start();
        }
        return new InterProcessMutex(curatorFramework,key);
    }


}
